package com.liuhm.bfs;

import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 修改结构
 *
 * @author liuhaomin
 * @date 2020/12/30
 */
@Data
public class Dag3 implements Serializable {

    private static final long serialVersionUID = 3247378463655231751L;
    private Map<String, VertexVersion> keyMap;
    private Map<String, VertexVersion> valueMap;

    public Dag3() {
        this.keyMap = new HashMap<>();
        this.valueMap = new HashMap<>();
    }

    public void addEdge(String from,String fromValue,boolean fromCalc, String to, String toValue,boolean toCalc){
        VertexVersion vFrom= keyMap.get(from)!=null?keyMap.get(from):new VertexVersion(from,fromValue,fromCalc);
        VertexVersion vTo = keyMap.get(to)!=null?keyMap.get(to):new VertexVersion(to,toValue,toCalc);
        vFrom.getChildren().add(vTo);
        vTo.getParents().add(vFrom);
        keyMap.put(from,vFrom);
        keyMap.put(to,vTo);
        if( valueMap.get(fromValue) != null ){
            if(valueMap.get(fromValue).getParents().size()>0){
                valueMap.get(fromValue).getParents().forEach(vertex->{
                    long count = keyMap.get(vertex.getKey()).getChildren().stream().filter(data -> data.getKey().equals(vFrom.getKey())).count();
                    if( count == 0 ){
                        vertex.setParented(true);
                        keyMap.get(vertex.getKey()).getChildren().add(vFrom);
                        vFrom.getParents().add(vertex);
                    }
                });
            }
        }else {
            valueMap.put(fromValue,vFrom);
        }
        if( valueMap.get(toValue) == null ){
            valueMap.put(toValue,vTo);
        }
    }

    public List<VertexVersion> getRoot(){
        List<VertexVersion> result = new ArrayList<>();
        this.keyMap.forEach((k,v)->{
            if(v.getParents().size()==0){
                result.add(v);
            }
        });
        return result;
    }
    public List<VertexVersion> getChildrenRoot(){
        List<VertexVersion> result = new ArrayList<>();
        this.keyMap.forEach((k,v)->{
            if(v.getChildren().size()==0){
                result.add(v);
            }
        });
        return result;
    }




}

